package com.usoft;

import akka.dispatch.ExecutionContexts;
import akka.dispatch.Futures;
import akka.dispatch.OnSuccess;
import akka.japi.Function2;
import scala.concurrent.ExecutionContextExecutorService;
import scala.concurrent.Future;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

/**
 * Futures.reduce
 * Created by liyanxin on 2015/1/9.
 */
public class ComposeFuture4 {

    public static void main(String args[]) {
        ExecutionContextExecutorService ec = ExecutionContexts.
                fromExecutorService(Executors.newCachedThreadPool());
        //A sequence of Futures, in this case Strings
        List<Future<String>> listOfFutureInts = new ArrayList<Future<String>>(10);
        for (int i = 0; i < 10; i++) {
            Future<String> item = Futures.successful(String.valueOf(i));
            listOfFutureInts.add(item);
        }

        /**
         * In some cases you don’t have a start-value and you’re able to use the value of the first completing Future in the
         * sequence as the start-value, you can use reduce, it works like this:
         */
        Future<Object> resultFuture = Futures.reduce(listOfFutureInts,
                new Function2<Object, String, Object>() {
                    @Override
                    public Object apply(Object arg1, String arg2) throws Exception {
                        return arg1 + arg2;
                    }
                }, ec);
        resultFuture.onSuccess(new OnSuccess<Object>() {
            @Override
            public void onSuccess(Object result) throws Throwable {
                System.out.println(result);
            }
        }, ec);
    }

}
